<template>
  <div>
    <!-- 当添加属性值时 三级分类下拉框禁用 -->
    <CategorySelector :disabled="isListView === false"></CategorySelector>

    <el-card v-if="isListView" style="margin-top: 20px">
      <template #header>
        <el-button
          type="primary"
          icon="ele-Plus"
          :disabled="category3Id === ''"
          @click="toggleToAddOrEditViewHandler()"
          >添加属性</el-button
        >
      </template>

      <el-table :data="attrs">
        <el-table-column
          width="100"
          label="序号"
          type="index"
        ></el-table-column>
        <el-table-column
          width="100"
          label="属性名称"
          prop="attrName"
        ></el-table-column>
        <el-table-column label="属性值名称列表">
          <template #="{ row }">
            <el-tag
              v-for="attrValue in row.attrValueList"
              :key="attrValue.id"
              style="margin-right: 10px"
              type="success"
              >{{ attrValue.valueName }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column width="200" label="操作">
          <template #="{ row }">
            <el-button
              type="warning"
              icon="ele-Edit"
              @click="toggleToAddOrEditViewHandler(row)"
            ></el-button>
            <el-button type="danger" icon="ele-Delete"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card v-else style="margin-top: 20px">
      <el-form inline>
        <el-form-item label="属性名">
          <el-input
            v-model="formData!.attrName"
            clearable
            @blur="enterAttrNameHandler"
            @keydown.enter="enterAttrNameHandler"
            ref="attrNameInputRef"
          />
        </el-form-item>
      </el-form>

      <div>
        <el-button
          type="primary"
          @click="addAttrValueHandler"
          :disabled="formData?.attrName == ''"
          >添加属性值</el-button
        >
        <el-button @click="isListView = true">取消</el-button>
      </div>

      <el-table style="margin: 20px 0" :data="formData!.attrValueList">
        <el-table-column
          width="100"
          label="序号"
          type="index"
        ></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row }">
            <span
              v-if="row != currentEditAttrValue"
              @click="enterFocisStatusHandler(row)"
              >{{ row.valueName }}</span
            >
            <el-input
              v-else
              v-model="row.valueName"
              ref="attrValueInputRef"
              @blur="enterAttrValueHandler"
              @keydown.enter="enterAttrValueHandler"
            />
          </template>
        </el-table-column>
        <el-table-column width="150" label="操作">
          <template #="{ row }">
            <el-button
              type="danger"
              icon="ele-Delete"
              @click="removeAttrValueHandler(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <div>
        <el-button
          type="primary"
          @click="saveHandler"
          :disabled="formData!.attrName == '' ||
        formData!.attrValueList.length ===0"
          >保存</el-button
        >
        <el-button @click="isListView = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "ProductAttr",
});
</script>
<script lang="ts" setup>
//三级分类组件
import CategorySelector from "@/components/CategorySelector/index.vue";
import { watch, ref, nextTick } from "vue";
import * as apis from "@/api/attr";
//storeToRefs--跟元数据永久关联
import { storeToRefs } from "pinia";
//仓库
import { useCategorySelectorStore } from "@/stores/categorySelector";
//提示框
import { ElMessage } from "element-plus";
//数据类型
import type { IAttr, IAddOrEditAttr, IAttrValue } from "@/api/attr";

//调用仓库
const categorySelectorStore = useCategorySelectorStore();

//将仓库内需要用的数据结构
const { category1Id, category2Id, category3Id } = storeToRefs(
  categorySelectorStore
);

//平台属性列表数据--三级列表请求来的平台属性数据
const attrs = ref<IAttr[]>([]);

//显示列表或者添加列表
const isListView = ref(true);

//当前编辑或添加的属性数据
const formData = ref<IAddOrEditAttr>();

//属性值输入框DOM元素
const attrValueInputRef = ref<HTMLInputElement>();

//属性名输入框DOM元素
const attrNameInputRef = ref<HTMLInputElement>();

//编辑状态的数据AttrValue
const currentEditAttrValue = ref<Partial<IAttrValue>>();

//通过category3Id获取attrs--平台属性数据
async function getAttrList() {
  //当categoryId为空时 重置attrs
  if (category3Id.value === "") return (attrs.value = []);
  //发送请求 获取attrs数据
  try {
    attrs.value = await apis.requestAttrInfoList(
      category1Id.value as number,
      category2Id.value as number,
      category3Id.value as number
    );
  } catch (e) {
    ElMessage.error("请求平台属性列表失败");
  }
}

//当category3Id发生改变时 再次调用初始化函数获取数据
//默认触发一次
watch(category3Id, getAttrList, {
  immediate: true,
});
//添加属性事件，初次初始化formData
function toggleToAddOrEditViewHandler(data?: IAttr) {
  console.log("点击了");
  isListView.value = false;

  if (!data) {
    formData.value = {
      categoryId: category3Id.value as number,
      categoryLevel: 3,
      attrName: "",
      attrValueList: [],
    };
  } else {
    formData.value = data;
  }
}

//添加属性是 检测输入属性名是否已存在
//编辑时 修改属性数据会冲突 现在原数组剔除当前数据
function enterAttrNameHandler() {
  const isExists = attrs.value.find(
    (attr) =>
      attr.id != formData.value!.id && attr.attrName == formData.value!.attrName
  );
  if (isExists) {
    ElMessage.error("属性名重复");
    formData.value!.attrName = "";
    nextTick(() => {
      attrValueInputRef.value!.focus();
    });
  }
}

//在属性数据内添加属性值数据
function addAttrValueHandler() {
  const data = {
    valueName: "",
  };
  formData.value?.attrValueList.push(data);
  currentEditAttrValue.value = data;
  //默认获取焦点
  nextTick(() => {
    attrValueInputRef.value?.focus();
  });
}

//属性值提交 清空currentEditAttrValue-input输入时数据
function enterAttrValueHandler() {
  if (currentEditAttrValue.value!.valueName === "") {
    formData.value!.attrValueList = formData.value!.attrValueList.filter(
      (item) => item != currentEditAttrValue.value
    );
    currentEditAttrValue.value = undefined;
    return;
  }

  const isExists = formData.value?.attrValueList.find(
    (item) =>
      item != currentEditAttrValue.value &&
      item.valueName == currentEditAttrValue.value?.valueName
  );

  if (isExists) {
    ElMessage.error("属性值不能重复");
    currentEditAttrValue.value!.valueName = "";
    nextTick(() => {
      attrValueInputRef.value!.focus();
    });
  } else {
    currentEditAttrValue.value = undefined;
  }
}

//属性值数据重新赋值 当点击对应属性值时  currentEditAttrValue 赋值为该行数据的最新值 满足v-if条件 变成input状态
function enterFocisStatusHandler(val: IAttrValue) {
  currentEditAttrValue.value = val;
  nextTick(() => {
    attrValueInputRef.value?.focus();
  });
}

//删除
function removeAttrValueHandler(data: IAttrValue) {
  formData.value!.attrValueList = formData.value!.attrValueList.filter(
    (item) => item != data
  );
}

// 提交数据
async function saveHandler() {
  try {
    if (formData.value) {
      await apis.requestSaveOrUpdateAttr(formData.value);
      ElMessage.success("保存成功");
      isListView.value = true;
      getAttrList();
    }
  } catch (e) {
    ElMessage.error("保存失败");
  }
}
</script>
